package com.ruoyi.vehicle.respository;


import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.time.Duration;
import java.util.List;

// 自定义的Redis存储实现
public class RedisChatMemoryStore implements ChatMemoryStore {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public List<ChatMessage> getMessages(Object memoryId) {

        // 从Redis中获取消息
        String json = redisTemplate.opsForValue().get(memoryId);

        List<ChatMessage> chatMessages = ChatMessageDeserializer.messagesFromJson(json);

        return chatMessages;
    }

    @Override
    public void updateMessages(Object memoryId, List<ChatMessage> list) {
      //更新会话消息
        //1.把list转换成json数据
        String json = ChatMessageSerializer.messagesToJson(list); // 把消息列表转换成json字符串
        //2.把json数组存储到redis中                         存储到redis中，设置过期时间1天
        redisTemplate.opsForValue().set(memoryId.toString(), json, Duration.ofDays(1));


    }

    @Override
    public void deleteMessages(Object memoryId) {

        redisTemplate.delete(memoryId.toString());
        //删除会话消息
        //1.根据memoryId删除redis中的数据
    }
}
